package org.greatstorm.service;

import java.util.List;

import org.greatstorm.dao.CategoryDao;
import org.greatstorm.entity.Category;
import org.greatstorm.entity.EntityObject;
import org.greatstorm.exception.KeyRepeatException;
import org.greatstorm.tx.Transaction;
import org.greatstorm.tx.TransactionManager;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class CategoryManager {
	@Inject
	CategoryDao cateDao;

	public void addCategory(String name) {
		Transaction tx = TransactionManager.getTransaction();
		tx.beginTransaction();

		// check whether the adding category exists
		EntityObject ret = cateDao.getCategoryByName(name);

		if (ret != null) {
			throw new KeyRepeatException("category name has existed!");
		}

		EntityObject category = new EntityObject();
		category.put(Category.CATEGORY_NAME, name);
		category.put(Category.ARTICLE_COUNT, 0);
		cateDao.save(category);
	}

	public EntityObject getCategoryByName(String name) {
		return cateDao.getCategoryByName(name);
	}

	public void deleteAll() {
		cateDao.deleteAll();
	}

	public List<EntityObject> getAllCategories() {
		return cateDao.getAll();
	}

	public EntityObject getCategoryByKey(String categoryKey) {
		return cateDao.getEntityByKey(categoryKey);
	}
}
